//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by 张子国 on 15/11/20.
//  Copyright © 2015年 张子国. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        send()
    }
    @objc private func send() {
    
        let urlString = "2/statuses/update.json"
        guard let token = UserAccountViewModel().token else{
        SVProgressHUD.showErrorWithStatus("主银，您还未登录")
            return
        }
    
        let parameters = ["access_token": token,"status": textView.text]
        NetworkTools.sharedTools.requestJsonDict(HTTPMethod.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrprlip)
                return
            }
            SVProgressHUD.showSuccessWithStatus("成功")
            self.dismissViewControllerAnimated(true, completion: nil)
            print(result)
        }
        
        
    }
    private func setupUI() {
        setNavBar()
        setTexView()
        setupTool()
        
        //注册通知
        registerNsnotification()
        
    }
    private func registerNsnotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChang:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 实现通知方法
    @objc private func keyboardFrameWillChang(n : NSNotification){
        //print(n)
        //动画事件
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey]as! NSValue).CGRectValue()
        //键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }


private func setNavBar() {
    let titleView = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 40))
    let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
    let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
    
    titleView .addSubview(titleLabel)
    titleLabel.addSubview(nameLabel)
    
    //设置约束
    titleLabel.snp_makeConstraints { (make) -> Void in
        make.top.equalTo(titleView.snp_top)
        make.centerX.equalTo(titleView.snp_centerX)
    }
    nameLabel.snp_makeConstraints { (make) -> Void in
        make.bottom .equalTo(titleView.snp_bottom)
        make.centerX.equalTo(titleView.snp_centerX)
    }
    
    
    navigationItem.titleView = titleView
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
    self.navigationItem.rightBarButtonItem?.enabled = false
    
}



private lazy var textView : UITextView = {
    let tex = UITextView()
    //设置代理 隐藏占位字符
    tex.delegate = self
    tex.font = UIFont.systemFontOfSize(18)
    tex.textColor = UIColor.darkGrayColor()
    
    //设置键盘隐藏模式
    tex.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
    
    //设置弹簧效果开启
    tex.alwaysBounceVertical = true
    tex.backgroundColor = UIColor.lightGrayColor()
    
    return tex
}()

//设置占位label
private lazy var placeLabel : UILabel = UILabel(title: "分享新鲜事", size: 14, color: UIColor.cyanColor())

//添加toolbar
private lazy var toolBar : UIToolbar = UIToolbar()

}
extension ComposeViewController : UITextViewDelegate{
    func textViewDidChangeSelection(textView: UITextView) {
        //占位字符隐藏
        placeLabel.hidden = textView.hasText()
        //发布按钮隐藏
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
extension ComposeViewController {
    
    private func setupTool() {
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        //设置toolbar
        var items = [UIBarButtonItem]()
        
        //添加UIBarButtonItem
        let itemSeting = [["imageName":"compose_toolbar_picture"],["imageName":"compose_mentionbutton_background"],["imageName":"compose_trendbutton_background"],["imageName":"compose_emoticonbutton_background"],["imageName":"compose_add_background"]]
        
        for dict in itemSeting {
            
            let item = UIBarButtonItem(imageName: dict["imageName"]!)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action:nil)
            items.append(space)
            items.append(item)
            
            
        }
        //移除最后一个弹簧
        items.removeFirst()
        toolBar.items = items
    }
    
    private func setTexView() {
        view .addSubview(textView)
        textView.backgroundColor = UIColor.lightGrayColor()
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        
        textView .addSubview(placeLabel)
        
        //设置label约束
        placeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(4)
        }
    }
    
    
}


